package com.elite.scheduler.jobs;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.elite.scheduler.entity.Config;
import com.elite.scheduler.entity.ESLogClear;
import com.elite.scheduler.entity.Result;
import com.elite.scheduler.internal.Constant;
import com.elite.scheduler.utils.*;
import com.elite.scheduler.utils.security.sm.SM3Util;
import com.elite.scheduler.utils.xhr.XHRPoolService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.MediaType;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Component
public class SchedulerTypeJob {

    private static String appName;
    
    @Autowired
    CommonUtil commonUtil;

    @Lazy
    @Autowired
    SchedulerUtil schedulerUtil;

    @Autowired
    ReporterUtil reporterUtil;

    @Value("${spring.application.name:scheduler}")
    public void setAppName(String appName) {
        SchedulerTypeJob.appName = appName;
    }

    @Autowired
    Config config;

    public static final String STRING_OBJECT_SQL = "objectsql";
    public static final String STRING_OBJECT_COLUMN = "objectcolumn";
    public static final String STRING_INDEX = "index";

    private static XHRPoolService xhrService;
    private static ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    public void setXhrService(XHRPoolService xhrService) {
        this.xhrService = xhrService;
    }

    @Autowired
    public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
        this.threadPoolExecutor = threadPoolExecutor;
    }

    private static RestTemplateUtil restTemplateUtil;

    @Autowired
    public void setRestTemplateService(RestTemplateUtil restTemplateUtil) {
        SchedulerTypeJob.restTemplateUtil = restTemplateUtil;
    }

    @Resource
    private JdbcTemplate jdbcTemplate;

    public Result EmailJob(Map<String, Object> schedulerTemp, String epid) {
        String timer_guid = null;
        String objectStr = (String) schedulerTemp.get(STRING_OBJECT_SQL);
        String sendStr = (String) schedulerTemp.get("sendsql");
        try {
            if (commonUtil.authSelect(objectStr)) {
                List<Map<String, Object>> objectList = commonUtil.sqlQueryForList(epid, objectStr, null);
                log.debug("发送邮件对象size():objectList:" + objectList.size());
                if (objectList != null && objectList.size() > 0) {
                    JSONObject contentJson = new JSONObject();
                    timer_guid = (String) schedulerTemp.get("timer_guid");
                    String emailTitle = (String) schedulerTemp.get("title");
                    String sendmodel = (String) schedulerTemp.get("sendmodel");
                    JSONObject paramObj = new JSONObject();
                    paramObj.put("epid", TimerConfigParamsUtil.epid);

                    paramObj.put("staff_id", TimerConfigParamsUtil.mailStaffId);
                    paramObj.put("group_id", TimerConfigParamsUtil.mailGroupId);
                    paramObj.put("type", "mail");
                    for (Map<String, Object> objectTemp : objectList) {
                        // 将对象信息作为模板参数传入模板
                        paramObj.put("subject", SchedulerUtil.replaceVar(emailTitle, objectTemp));
                        contentJson.put("objectInfo", commonUtil.transDateWithMap(objectTemp));
                        String objectcolumn = (String) schedulerTemp.get(STRING_OBJECT_COLUMN);
                        String email = (String) objectTemp.get(objectcolumn);
                        log.debug("objectcolumn:" + objectcolumn + " email:" + email);
                        if (StringUtil.isNotNull(email)) {
                            paramObj.put("recipient", email);
                            // 发送内容到该对象Email 调tony接口
                            String sendText = (String) schedulerTemp.get("sendtext");
                            if ("TEXT".equalsIgnoreCase(sendmodel)) {
                                paramObj.put("filePath", sendText);
                                paramObj.put("contentType", "1");
                            } else if ("带条件SQL".equalsIgnoreCase(sendmodel)) {
                                String templetfile = (String) schedulerTemp.get("templatefile");
                                if (StringUtil.isNotNull(templetfile)) {
                                    paramObj.put("filePath", templetfile);
                                } else {
                                    paramObj.put("filePath", "");
                                }
                                if (sendStr != null && commonUtil.authSelect(sendStr)) {
                                    String[] dataSqlList = new String[1];
                                    if (sendStr.indexOf(";") > 0) {
                                        dataSqlList[0] = sendStr;
                                    } else {
                                        dataSqlList = sendStr.split(";");
                                    }
                                    String conditColumn = (String) schedulerTemp.get("conditcolumn");
                                    contentJson = (JSONObject) schedulerUtil.packContentJsonObj(contentJson,
                                            dataSqlList, conditColumn, objectTemp, epid, false, sendText);
                                    log.debug("contentJson:" + contentJson);
                                    String encodeRequParam = URLEncoder.encode(contentJson.toString(), "utf-8");
                                    paramObj.put("contentJson", encodeRequParam);
                                    paramObj.put("contentType", "0");
                                } else {
                                    log.error("error.sendsql 有误");
                                }
                            } else {
                                if (sendStr != null && commonUtil.authSelect(sendStr)) {
                                    String[] dataSqlList = new String[1];
                                    if (sendStr.indexOf(";") > 0) {
                                        dataSqlList[0] = sendStr;
                                    } else {
                                        dataSqlList = sendStr.split(";");
                                    }
                                    String conditColumn = (String) schedulerTemp.get("conditcolumn");
                                    sendText = schedulerUtil.packContentJsonObj(contentJson, dataSqlList, conditColumn,
                                            objectTemp, epid, true, sendText).toString();
                                    log.debug("conditColumn: " + conditColumn + " sendText:" + sendText);
                                    paramObj.put("filePath", sendText);
                                    paramObj.put("contentType", "1");
                                } else {
                                    log.error("error.sendsql 有误");
                                }
                            }
                            paramObj.put("mailFrom", config.getMailFrom());
                            Result sendEmailResult = SchedulerUtil.sendEmail(config.getMailServiceUrl(), paramObj, timer_guid);
                            if (sendEmailResult.getCode() > -1) {
                                String replyOpera = (String) schedulerTemp.get("replyopera");
                                log.debug("replyOpera:" + replyOpera);
                                if (StringUtil.isNotNull(replyOpera)) {
                                    String[] replyArr = replyOpera.split("\n");
                                    for (String reply : replyArr) {
                                        if (StringUtil.isNotNull(reply)) {
                                            int result = schedulerUtil.sendEmailReply(objectTemp, reply);
                                            log.debug("发送邮件完成之后回写sql数据" + (result != 0 ? "成功" : "失败") + " 更新了【" + result
                                                    + "】条记录。");
                                        } else {
                                            log.debug("无需回写");
                                        }
                                    }
                                }
                            } else {
                                return new Result(Result.ERROR, sendEmailResult.getMessage());
                            }
                        } else {
                            log.error("email对象为空， 请检查对象字段");
                        }
                    }
                } else {
                    log.debug("timer_guid:" + timer_guid + " objectStr:" + objectStr + " have not 对象需要发送");
                    return new Result(Result.ERROR, "objectsql:" + objectStr + " have not 对象需要发送");
                }
            } else {
                log.debug("timingtaskGuid:" + timer_guid + " objectStr:" + objectStr + "  or  sendStr:" + sendStr
                        + "  不合法");
                return new Result(Result.ERROR, " objectStr:" + objectStr + "or  sendStr:" + sendStr + "  不合法");
            }
            return new Result(Result.SUCCESS);
        } catch (Exception e) {
            log.error("EmailJob.e", e);
            return new Result(Result.ERROR, e.getMessage());
        }
    }

    public Result sendSms(Map<String, Object> schedulerTemp, String epid) {
        String timerGuid = null;
        try {
            timerGuid = (String) schedulerTemp.get("timer_guid");
            String smsContent = (String) schedulerTemp.get("sendtext");
            String objectsql = (String) schedulerTemp.get(STRING_OBJECT_SQL);
            String objectColumn = (String) schedulerTemp.get(STRING_OBJECT_COLUMN);
            List<Map<String, Object>> objectList = commonUtil.sqlQueryForList(epid, objectsql, null);
            for (Map<String, Object> objectTemp : objectList) {
                String phoneNo = (String) objectTemp.get(objectColumn);
                log.debug("send sms phoneNo:" + phoneNo + "  smsContent:" + smsContent);
                if (StringUtil.isNotNull(phoneNo)) {
                    String requestParam = "sms_content=" + smsContent + "&sms_phone=" + phoneNo;
                    SchedulerUtil.sendSms(requestParam, timerGuid);
                }
            }
            return new Result(Result.SUCCESS);
        } catch (Exception e) {
            log.error(timerGuid + "sendSms.e", e);
            return new Result(Result.ERROR, e.getMessage());
        }
    }

    public Result callAPIJob(Map<String, Object> schedulerTemp) {
        String timerGuid = null;
        try {
            Config config = (Config) SpringContextUtil.getBean("config");
            if (config != null) {
                timerGuid = StringUtil.parseNull(schedulerTemp.get("timer_guid"));
                String interfaceType = StringUtil.parseNull(schedulerTemp.get("interfacetype"));
                String interfaceURL = StringUtil.parseNull(schedulerTemp.get("interfaceurl"));
                log.debug("callApi任务编号: {}, 请求类型: {}, 请求地址: {}", timerGuid, interfaceType, interfaceURL);
                if (!(StringUtil.isNotNull(interfaceURL)
                        && (interfaceURL.startsWith("http:") || interfaceURL.startsWith("https:")))) {
                    return new Result(Result.ERROR, interfaceURL + "   接口地址有误");
                }
                Map<String, String> headers = new HashMap<>();
                headers.put("APP_NAME", appName);
                threadPoolExecutor.execute(() -> {
                    String jobStatus;
                    String insertLogSql = "INSERT INTO SCHEDULER_LOG(LOG_ID, JOB_NAME, JOB_TYPE, JOB_ID, JOB_STATUS, START_TIME, STOP_TIME, DURATION, JOB_RESULT_MSG, EXCEPTION_INFO, CREATEDDATE, CREATEDBY, MODIFYDATE, MODIFYBY, JOB_PARAM) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    String logId = IdUtil.getSnowflakeNextIdStr();
                    String jobName = StringUtil.parseNull(schedulerTemp.get("timername"));
                    String jobType = "CALLAPI";
                    String jobId = StringUtil.parseNull(schedulerTemp.get("timer_guid"));
                    Date startTime = new Date();
                    Date stopTime;
                    String jobResultMsg = "";
                    String exceptionInfo = "";
                    String intertfacePostParams = "";
                    try {
                        String responseString = "";
                        if (StringUtil.isNotNull(interfaceType) && "GET".equalsIgnoreCase(interfaceType)) {
                            intertfacePostParams = "";
                            responseString = restTemplateUtil.getForString(interfaceURL, headers);
                        } else {
                            intertfacePostParams = StringUtil.parseNull(schedulerTemp.get("intertfacepostparams"));
                            log.debug("callApi任务编号: {}, post请求入参: {}", jobId, intertfacePostParams);
                            responseString = restTemplateUtil.postForString(interfaceURL, intertfacePostParams, headers);
                        }
                        stopTime = new Date();
                        jobStatus = "0";
                        log.debug("callApi任务编号: {}, 请求返回结果: {}", jobId, responseString);
                        jobResultMsg = StrUtil.subWithLength(responseString, 0, 2000);;
                    } catch (Exception e) {
                        jobStatus = "1";
                        stopTime = new Date();
                        log.error("callApi任务编号: {}, 请求异常: {}", jobId, e.getMessage(), e);
                        exceptionInfo = StrUtil.subWithLength(e.getMessage(), 0, 2000);
                    }
                    long duration = stopTime.getTime() - startTime.getTime();
                    Object[] args = new Object[]{logId, jobName, jobType, jobId, jobStatus, startTime, stopTime, duration, jobResultMsg, exceptionInfo, new Date(), "admin", new Date(), "admin", intertfacePostParams};
                    jdbcTemplate.update(insertLogSql, args);
                });
            }
            return new Result(Result.SUCCESS);
        } catch (Exception e) {
            log.error("callApi任务编号: {}, 发生异常: {}", timerGuid, e.getMessage(), e);
            return new Result(Result.ERROR, e.getMessage());
        }
    }

    public Result objectCallAPIJob(Map<String, Object> schedulerTemp, String epid) {
        String jobStatus;
        String logId = IdUtil.getSnowflakeNextIdStr();
        String jobName = StringUtil.parseNull(schedulerTemp.get("timername"));
        String jobType = "OBJECTSQL-CALLAPI";
        String jobId = StringUtil.parseNull(schedulerTemp.get("timer_guid"));
        Date startTime = new Date();
        String exceptionInfo = "";
        String jobResultMsg = "";
        Date stopTime;
        long duration;
        String insertLogSql = "INSERT INTO SCHEDULER_LOG(LOG_ID, JOB_NAME, JOB_TYPE, JOB_ID, JOB_STATUS, START_TIME, STOP_TIME, DURATION, JOB_RESULT_MSG, EXCEPTION_INFO, CREATEDDATE, CREATEDBY, MODIFYDATE, MODIFYBY, JOB_PARAM) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try {
            String interfaceType = StringUtil.parseNull(schedulerTemp.get("interfacetype"));
            String objectSql = StringUtil.parseNull(schedulerTemp.get(STRING_OBJECT_SQL));
            String objectColumn = StringUtil.parseNull(schedulerTemp.get(STRING_OBJECT_COLUMN));
            String interfaceURL = StringUtil.parseNull(schedulerTemp.get("interfaceurl"));
            log.debug("objectCallAPIJob任务编号: {}, 请求类型: {}, 请求地址: {}, 请求sql: {}, objectColumn: {}", jobId, interfaceType, interfaceURL, objectSql, objectColumn);
            if (!(StringUtil.isNotNull(interfaceURL)
                    && (interfaceURL.startsWith("http:") || interfaceURL.startsWith("https:")))) {
                stopTime = new Date();
                duration = stopTime.getTime() - startTime.getTime();
                jobStatus = "1";
                jobResultMsg = interfaceURL + "接口地址有误";
                Object[] args = new Object[]{logId, jobName, jobType, jobId, jobStatus, startTime, stopTime, duration, jobResultMsg, exceptionInfo, new Date(), "admin", new Date(), "admin", ""};
                jdbcTemplate.update(insertLogSql, args);
                return new Result(Result.ERROR, jobResultMsg);
            }
            Map<String, String> headers = new HashMap<>();
            headers.put("APP_NAME", "scheduler");
            List<Map<String, Object>> objectList = commonUtil.sqlQueryForList(epid, objectSql, null);
            for (Map<String, Object> objectTemp : objectList) {
                String tempInterfaceURL = interfaceURL;
                if (StringUtil.isNotNull(objectColumn) && objectColumn.split(";").length > 0) {
                    String[] objectColumnArr = objectColumn.split(";");
                    for (String objectColumnStr : objectColumnArr) {
                        String tempStr = (String) objectTemp.get(objectColumnStr);
                        tempInterfaceURL = tempInterfaceURL.replace("${" + objectColumnStr + "}", tempStr);
                    }
                    if (StringUtil.isNotNull(interfaceType) && "GET".equalsIgnoreCase(interfaceType)) {
                        String responseGetParams = xhrService.get(tempInterfaceURL, null, headers);
                        log.debug("objectCallAPIJob任务编号: {}, get请求返回结果: {}", jobId, responseGetParams);
                    } else {
                        String postParams = StringUtil
                                .parseNull(schedulerTemp.get("intertfacepostparams"));
                        log.debug("objectCallAPIJob任务编号: {}, post请求入参: {}", jobId, postParams);
                        String responsePostParams = xhrService.post(tempInterfaceURL, postParams,
                                MediaType.APPLICATION_JSON_VALUE, headers);
                        log.debug("objectCallAPIJob任务编号: {}, post请求返回结果: {}", jobId, responsePostParams);
                    }
                }
            }
            stopTime = new Date();
            jobStatus = "0";
            duration = stopTime.getTime() - startTime.getTime();
            jobResultMsg = "成功";
            Object[] args = new Object[]{logId, jobName, jobType, jobId, jobStatus, startTime, stopTime, duration, jobResultMsg, exceptionInfo, new Date(), "admin", new Date(), "admin", JSONObject.toJSONString(objectList)};
            jdbcTemplate.update(insertLogSql, args);
            return new Result(Result.SUCCESS);
        } catch (Exception e) {
            stopTime = new Date();
            jobStatus = "1";
            duration = stopTime.getTime() - startTime.getTime();
            exceptionInfo = e.getMessage();
            Object[] args = new Object[]{logId, jobName, jobType, jobId, jobStatus, startTime, stopTime, duration, jobResultMsg, exceptionInfo, new Date(), "admin", new Date(), "admin", ""};
            jdbcTemplate.update(insertLogSql, args);
            log.error("objectSql-callApi类型任务执行异常: {}, jobId: {}", e.getMessage(), jobId, e);
            return new Result(Result.ERROR, e.getMessage());
        }
    }

    public Result callServerCmd(Map<String, Object> schedulerTemp) {
        String timerGuid = null;
        try {
            timerGuid = StringUtil.parseNull(schedulerTemp.get("timer_guid"));
            org.json.JSONObject tokenBody = commonUtil.getNgsToken(0);
            log.debug("callServerCmd.ngsToken:" + tokenBody);
            String token = tokenBody.optString(Constant.STRING_TOKEN);
            int digest = tokenBody.optInt("ordindex");
            String serverCmdKey = StringUtil.parseNull(schedulerTemp.get("servercmdkey"));
            String servercmdparam = StringUtil.parseNull(schedulerTemp.get("servercmdparam"));
            log.debug("callServerCmd.serverCmdKey:" + serverCmdKey + " servercmdparam:" + servercmdparam);
            JdbcTemplate jt = (JdbcTemplate) SpringContextUtil.getBean("jdbcTemplate");
            List<Map<String, Object>> list = jt.queryForList("select outs from tab_srvcmd t where t.CMDGUID = ?",
                    serverCmdKey);
            String servercmdoutputparam = (String) list.get(0).get("outs");
            String threadId = System.currentTimeMillis() + "";
            String dbPool = token.split("\\$").length > 1 ? token.split("\\$")[1] : "";
            JSONObject callCmdParams = new JSONObject();
            callCmdParams.put(Constant.STRING_TOKEN, token);
            callCmdParams.put("digest", digest);
            callCmdParams.put("dbPool", dbPool);
            callCmdParams.put("id", serverCmdKey);
            callCmdParams.put("threadId", threadId);
            JSONObject paraIn = new JSONObject();
            JSONObject insObj = new JSONObject();
            insObj.put("CMD_IN", servercmdparam);
            paraIn.put("ins", insObj);
            callCmdParams.put("params", paraIn);
            callCmdParams.put("outs", servercmdoutputparam);
            JSONObject req = new JSONObject();
            req.put(Constant.STRING_TOKEN, token);
            req.put("dbPool", dbPool);
            req.put("name", "Dyn2.ServerCmd.Run");
            req.put("data", JSON.toJSONString(callCmdParams.toString()));
            String bodyRequset = req.toString().replace("\\\\", "");
            log.debug("bodyRequset:" + bodyRequset);
            String signer = "";
            if ("sm3".equals(TimerConfigParamsUtil.xhrDigest)) {
                signer = SM3Util.hash(token.substring(digest) + bodyRequset);
            } else {
                signer = (DigestUtils.md5Hex(token.substring(digest) + bodyRequset));
            }
            Map<String, String> headers = new HashMap<>();
            headers.put("SIGNER", signer);
            headers.put("THREADID", threadId);
            String resultBodyStr = xhrService.post(TimerConfigParamsUtil.serverCmdURL, bodyRequset, "application/json", headers);
            JSONObject resultBody = JSONObject.parseObject(resultBodyStr);
            log.debug("resultBody:" + resultBody);
            int code = resultBody.getInteger("code");
            if (code == 1) {
                return new Result(Result.SUCCESS, null, resultBody);
            } else {
                return new Result(Result.ERROR, resultBody.getString("message"));
            }
        } catch (Exception e) {
            log.error(timerGuid + "callServerCmd.e", e);
            return new Result(Result.ERROR, e.getMessage());
        }
    }

    public Result executeSql(Map<String, Object> schedulerTemp) {
        String jobStatus;
        String logId = IdUtil.getSnowflakeNextIdStr();
        String jobName = StringUtil.parseNull(schedulerTemp.get("timername"));
        String jobType = "EXECUTE-SQL";
        String jobId = StringUtil.parseNull(schedulerTemp.get("timer_guid"));
        Date startTime = new Date();
        String exceptionInfo = "";
        Date stopTime;
        try {
            String objectSql = (String) schedulerTemp.get(STRING_OBJECT_SQL);
            int sqlUpdate = commonUtil.sqlUpdate(objectSql, null);
            log.debug("ExecuteSql执行sql: {}, result: {}", objectSql, sqlUpdate);
            stopTime = new Date();
            jobStatus = "0";
            long duration = stopTime.getTime() - startTime.getTime();
            String insertLogSql = "INSERT INTO SCHEDULER_LOG(LOG_ID, JOB_NAME, JOB_TYPE, JOB_ID, JOB_STATUS, START_TIME, STOP_TIME, DURATION, AFFECT_ROW, CREATEDDATE, CREATEDBY, MODIFYDATE, MODIFYBY) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            Object[] args = new Object[]{logId, jobName, jobType, jobId, jobStatus, startTime, stopTime, duration, sqlUpdate, new Date(), "admin", new Date(), "admin"};
            jdbcTemplate.update(insertLogSql, args);
            return new Result(Result.SUCCESS);
        } catch (Exception e) {
            jobStatus = "1";
            stopTime = new Date();
            long duration = stopTime.getTime() - startTime.getTime();
            exceptionInfo = e.getMessage();
            String insertLogSql = "INSERT INTO SCHEDULER_LOG(LOG_ID, JOB_NAME, JOB_TYPE, JOB_ID, JOB_STATUS, START_TIME, STOP_TIME, DURATION, EXCEPTION_INFO, CREATEDDATE, CREATEDBY, MODIFYDATE, MODIFYBY) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            Object[] args = new Object[]{logId, jobName, jobType, jobId, jobStatus, startTime, stopTime, duration, exceptionInfo, new Date(), "admin", new Date(), "admin"};
            jdbcTemplate.update(insertLogSql, args);
            log.error("executeSql类型任务执行异常: {}, jobId: {}", e.getMessage(), jobId, e);
            return new Result(Result.ERROR, e.getMessage());
        }
    }

    public Result ESLogClear() throws Exception {
        ESLogClear esLogClear = (ESLogClear) SpringContextUtil
                .getBean("esLogClear");
        String ESFindLogUrl = esLogClear.getESFindLogUrl();
        String ESDeleteLogUrl = esLogClear.getESDeleteLogUrl();
        String filePrefix = esLogClear.getFilePrefix();
        int keepDays = esLogClear.getKeepDays();
        String findResult = xhrService.get(ESFindLogUrl);
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> array = JSON.parseObject(findResult, new TypeReference<List<Map<String, Object>>>(){});
        Map<String, Object> headers = new HashMap<String, Object>();
        headers.put("Content-type", "application/json");
        headers.put("DataEncoding", "UTF-8");
        if (array.size() > 0) {
            String[] prefixs = filePrefix.split(";");
            for (String prefix : prefixs) {
                if (prefix.contains("*")) {
                    String s = prefix.replace("*", "");
                    List<Map<String, Object>> list = array.stream()
                            .filter(p -> StringUtil.parseNull(p.get(STRING_INDEX)).startsWith(s))
                            .collect(Collectors.toList());
                    for (Map<String, Object> temp : list) {
                        String index = (String) temp.get(STRING_INDEX);
                        if (!ESLogCheck(keepDays, s, index)) {
                            String result = xhrService.delete(ESDeleteLogUrl + index, headers);
                            log.debug("index : " + index + " 删除 " + result);
                        }
                    }
                } else {
                    List<Map<String, Object>> list = array.stream()
                            .filter(p -> StringUtil.parseNull(p.get(STRING_INDEX)).equals(prefix))
                            .collect(Collectors.toList());
                    for (Map<String, Object> temp : list) {
                        String index = (String) temp.get(STRING_INDEX);
                        String result = xhrService.delete(ESDeleteLogUrl + index, headers);
                        log.debug("index : " + index + " 删除 " + result);
                    }
                }
            }
        }
        return new Result(Result.SUCCESS);
    }

    public static boolean ESLogCheck(int keepDays, String prefix, String index) {
        boolean flag = false;
        for (int i = 0; i < keepDays; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -i);
            String format = DateUtils.format(calendar.getTime(), "MM-dd");
            if (index.equals(prefix + format)) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    // String token, String dbpool, String rptId,
//    public static Result reporterJob(Map<?, ?> plMap) {
//        try {
//            log.debug("reporterJob.plMap:" + plMap);
//            String token = (String) plMap.get(Constant.STRING_TOKEN);
//            int digest = StringUtil.parseInt(StringUtil.parseNull(plMap.get("digest")));
//            String rptName = (String) plMap.get("rptName");
//            String emailServicers = (String) plMap.get("emailServicers");
//            String emailCcReceiver = (String) plMap.get("emailCcReceiver");
//            String reporterReleaseGuid = (String) plMap.get("timerGuid");
//            plMap.remove("rptName");
//            plMap.remove("timerGuid");
//            plMap.remove("emailServicers");
//            String callType = "test".equals((String) plMap.get("callType")) ? "0" : "1";
//            plMap.remove("callType");
//            plMap.remove("schedulerModel");
//
//            String params = JSonUtils.parse(plMap);
//            String signer = "";
//            log.debug("TimerConfigParamsUtil.xhrDigest :" + TimerConfigParamsUtil.xhrDigest);
//            if ("sm3".equals(TimerConfigParamsUtil.xhrDigest)) {
//                signer = SM3Util.hash(token.substring(digest) + params);
//            } else {
//                signer = (DigestUtils.md5Hex(token.substring(digest) + params));
//            }
//            Map<String, String> headers = new HashMap<>();
//            headers.put("SIGNER", signer);
//            headers.put("APP_NAME", "scheduler");
//            byte[] data = xhrService.postForBytes(TimerConfigParamsUtil.reporterUrl, params, headers);
//            log.debug("signer:" + signer);
//            String filename = rptName + "-" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
//            String localStorage = TimerConfigParamsUtil.localStorage;
//            log.debug("filename:" + filename + "localStorage:" + localStorage);
//            if (StringUtil.isNotNull(TimerConfigParamsUtil.mailServiceUrl)) {
//                String remote = TimerConfigParamsUtil.reporterRemotePath;
//                String ngsUrl = TimerConfigParamsUtil.ngsUrl + "/fs/upload_";
//                log.debug("getNgsFSAuthToken.token: " + token + "  将文件通过ngs.fs接口上传  ngsUrl：" + ngsUrl + " -- remote:" + remote);
//                String fsUploadResult = ReporterUtil.uploadFileByByte(token, ngsUrl, data, remote, filename, TimerConfigParamsUtil.reportEukey);
//                log.debug("fsUploadResult:" + fsUploadResult);
//                JSONObject obj = JSONObject.parseObject(fsUploadResult);
//                if ("1".equals(obj.getString("code"))) {
//                    boolean sendFlag = true;
//                    String filepath = obj.getString("value");
//                    int count = ReporterUtil.saveReportRunRecord((String) plMap.get("rptId"), callType, filepath, plMap.get("paras").toString());
//                    log.debug("count：" + count + ", emailServicers:" + emailServicers);
//                    if (emailServicers != null && !emailServicers.isEmpty()) {
//                        JSONObject paramObj = new JSONObject();
//                        paramObj.put("epid", TimerConfigParamsUtil.epid);
//                        paramObj.put("subject", rptName);
//                        paramObj.put("staff_id", TimerConfigParamsUtil.mailStaffId);
//                        paramObj.put("group_id", TimerConfigParamsUtil.mailGroupId);
//                        paramObj.put("type", "mail");
//                        paramObj.put("filePath", "请查收该报表");
//                        paramObj.put("contentType", "1");
//                        paramObj.put("recipient", emailServicers);
//                        paramObj.put("recipient_cc", emailCcReceiver);
//                        paramObj.put("mailAttach", filepath);
//                        Result sendResult = SchedulerUtil.sendEmail(paramsConfig.getMailServiceUrl(), paramObj, reporterReleaseGuid);
//                        if (sendResult.getCode() != 1) {
//                            sendFlag = false;
//                        }
//                        if (sendFlag) {
//                            return new Result(Result.SUCCESS, "邮件发送成功");
//                        } else {
//                            return new Result(Result.ERROR, "邮件发送失败");
//                        }
//                    } else {
//                        log.debug("无需发送邮件");
//                    }
//                    return new Result(Result.SUCCESS, "测试任务成功");
//                } else {
//                    return new Result(Result.ERROR, "测试任务失败");
//                }
//            } else {
//                log.debug("无需发送邮件");
//            }
//
//        } catch (Exception e) {
//            log.error("reporterJob.e", e);
//            return new Result(Result.ERROR, "Internal error");
//        }
//        return null;
//    }

    public Result reporterJobV1(Map<?, ?> plMap) {
        try {
            log.debug("报表任务入参: {}", plMap);
            String rptName = (String) plMap.get("rptName");
            String emailServicers = (String) plMap.get("emailServicers");
            String emailCcReceiver = (String) plMap.get("emailCcReceiver");
            String emailContent = (String) plMap.get("emailcontent");
            String reporterReleaseGuid = (String) plMap.get("timerGuid");
            plMap.remove("rptName");
            plMap.remove("timerGuid");
            plMap.remove("emailServicers");
            String callType = "test".equals((String) plMap.get("callType")) ? "0" : "1";
            plMap.remove("callType");
            plMap.remove("schedulerModel");

            String params = JSonUtils.parse(plMap);
            String token = (String) plMap.get(Constant.STRING_TOKEN);
            int digest = StringUtil.parseInt(StringUtil.parseNull(plMap.get("digest")));
            String signer = "";
            log.debug("调用ngs的签名算法为: " + TimerConfigParamsUtil.xhrDigest);
            if ("sm3".equals(TimerConfigParamsUtil.xhrDigest)) {
                signer = SM3Util.hash(token.substring(digest) + params);
            } else {
                signer = (DigestUtils.md5Hex(token.substring(digest) + params));
            }
            log.debug("签名signer: " + signer);
            Map<String, String> headers = new HashMap<>();
            headers.put("SIGNER", signer);
            headers.put("APP_NAME", "scheduler");
            byte[] data = xhrService.postForBytes(config.getReporterUrl(), params, headers);
            String filename = rptName + "_" + DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
            if (StringUtil.isNotNull(config.getMailServiceUrl())) {
                String remote = TimerConfigParamsUtil.reporterRemotePath;
                String ngsUrl = config.getUploadNgsUrl() + "/fs/upload_";
                log.debug("将文件通过ngs.fs接口上传ngsUrl: {}, filename: {}, remote: {}", ngsUrl, filename, remote);
                String fsUploadResult = reporterUtil.uploadFileByByteV1(ngsUrl, data, remote, rptName, filename, TimerConfigParamsUtil.reportEukey);
                log.debug("文件上传结果:" + fsUploadResult);
                JSONObject obj = JSONObject.parseObject(fsUploadResult);
                if ("1".equals(obj.getString("code"))) {
                    boolean sendFlag = true;
                    String filepath = obj.getString("value");
                    int count = reporterUtil.saveReportRunRecord((String) plMap.get("rptId"), callType, filepath, plMap.get("paras").toString());
                    log.debug("插入报表运行记录表结果: {}", count);
                    if (emailServicers != null && !emailServicers.isEmpty()) {
                        JSONObject paramObj = new JSONObject();
                        paramObj.put("epid", TimerConfigParamsUtil.epid);
                        paramObj.put("subject", rptName);
                        paramObj.put("staff_id", TimerConfigParamsUtil.mailStaffId);
                        paramObj.put("group_id", TimerConfigParamsUtil.mailGroupId);
                        paramObj.put("type", "mail");
                        paramObj.put("filePath", emailContent);
                        paramObj.put("contentType", "1");
                        paramObj.put("recipient", emailServicers);
                        paramObj.put("recipient_cc", emailCcReceiver);
                        paramObj.put("mailAttach", filepath);
                        paramObj.put("mailFrom", config.getMailFrom());
                        Result sendResult = SchedulerUtil.sendEmail(config.getMailServiceUrl(), paramObj, reporterReleaseGuid);
                        if (sendResult.getCode() != 1) {
                            sendFlag = false;
                        }
                        if (sendFlag) {
                            return new Result(Result.SUCCESS, "邮件发送成功");
                        } else {
                            return new Result(Result.ERROR, "邮件发送失败");
                        }
                    } else {
                        log.debug("无需发送邮件");
                    }
                    return new Result(Result.SUCCESS, "测试任务成功");
                } else {
                    return new Result(Result.ERROR, "测试任务失败");
                }
            } else {
                log.debug("无需发送邮件");
            }
        } catch (Exception e) {
            log.error("报表任务执行异常: {}", e.getMessage(), e);
            return new Result(Result.ERROR, e.getMessage());
        }
        return null;
    }


}
